<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../../stores/user'

const userStore = useUserStore()

// 个人信息表单
const profileForm = reactive({
  username: userStore.userInfo.username || '',
  email: userStore.userInfo.email || '',
  avatar: userStore.userInfo.avatar || '',
  bio: userStore.userInfo.bio || ''
})

// 密码修改表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 通知设置
const notificationSettings = reactive({
  emailNotification: true,
  systemNotification: true,
  courseNotification: true,
  messageNotification: true
})

// 表单校验规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 表单引用
const passwordFormRef = ref(null)

// 保存个人信息
const saveProfile = async () => {
  try {
    // TODO: 调用API保存个人信息
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请稍后重试')
  }
}

// 修改密码
const changePassword = async (formEl) => {
  if (!formEl) return
  
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        // TODO: 调用API修改密码
        ElMessage.success('密码修改成功')
        // 清空表单
        passwordForm.oldPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''
      } catch (error) {
        console.error('修改失败:', error)
        ElMessage.error('修改失败，请稍后重试')
      }
    } else {
      console.log('验证失败', fields)
      ElMessage.error('请检查表单填写是否正确')
    }
  })
}

// 保存通知设置
const saveNotificationSettings = async () => {
  try {
    // TODO: 调用API保存通知设置
    ElMessage.success('设置保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请稍后重试')
  }
}

// 上传头像
const handleAvatarSuccess = (response) => {
  profileForm.avatar = response.url
  ElMessage.success('头像上传成功')
}

const handleAvatarError = () => {
  ElMessage.error('头像上传失败')
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }
  return (isJPG || isPNG) && isLt2M
}
</script>

<template>
  <div class="settings-container">
    <el-tabs type="border-card">
      <!-- 个人信息设置 -->
      <el-tab-pane label="个人信息">
        <el-form :model="profileForm" label-width="100px">
          <el-form-item label="头像">
            <el-upload
              class="avatar-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><plus /></el-icon>
            </el-upload>
          </el-form-item>
          
          <el-form-item label="用户名">
            <el-input v-model="profileForm.username" />
          </el-form-item>
          
          <el-form-item label="邮箱">
            <el-input v-model="profileForm.email" />
          </el-form-item>
          
          <el-form-item label="个人简介">
            <el-input
              v-model="profileForm.bio"
              type="textarea"
              :rows="4"
              placeholder="请输入个人简介"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="saveProfile">保存</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 账号安全设置 -->
      <el-tab-pane label="账号安全">
        <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="100px"
        >
          <el-form-item label="原密码" prop="oldPassword">
            <el-input
              v-model="passwordForm.oldPassword"
              type="password"
              show-password
            />
          </el-form-item>
          
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              show-password
            />
          </el-form-item>
          
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              show-password
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="changePassword(passwordFormRef)">
              修改密码
            </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 通知设置 -->
      <el-tab-pane label="通知设置">
        <el-form :model="notificationSettings" label-width="200px">
          <el-form-item label="接收邮件通知">
            <el-switch v-model="notificationSettings.emailNotification" />
          </el-form-item>
          
          <el-form-item label="接收系统通知">
            <el-switch v-model="notificationSettings.systemNotification" />
          </el-form-item>
          
          <el-form-item label="接收课程相关通知">
            <el-switch v-model="notificationSettings.courseNotification" />
          </el-form-item>
          
          <el-form-item label="接收消息通知">
            <el-switch v-model="notificationSettings.messageNotification" />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="saveNotificationSettings">
              保存设置
            </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped>
.settings-container {
  padding: 20px;
}

.avatar-uploader {
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

:deep(.el-tabs__content) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style> 